//index.js
// var app = getApp()
Page({
  data: {
    specifications: {
      productName: "",
      labelTypeName: '',
      labels: [],
      info: {}
    },
    background: [],
    orderArr:[],
    indicatorDots: true,
    vertical: false,
    autoplay: false,
    interval: 2000,
    duration: 500,
    pageType: 1,
    balance: 0,
    // index
    userInfo: {},
    open: false, //是否打开红包
    page: true, //红包是否显示 
    orderOrBusiness: 'order',
    newsarr: [{
        id: 0,
        message: "本店新用户立减1元（在线支付专享）"
      },
      {
        id: 1,
        message: "本店新用户立减2元（在线支付专享）"
      },
      {
        id: 2,
        message: "本店新用户立减3元（在线支付专享）"
      },
      {
        id: 3,
        message: "本店新用户立减4元（在线支付专享）"
      },
      {
        id: 4,
        message: "本店新用户立减5元（在线支付专享）"
      }
    ],
    autoplay: true,
    interval: 3000,
    duration: 500,
    vertical: true,
    circular: true,

    menu: [{
        id: 0,
        name: "热销"
      },
      {
        id: 1,
        name: "新品"
      },
      {
        id: 2,
        name: "下午茶"
      },
      {
        id: 3,
        name: "滋味盖饭"
      },
      {
        id: 4,
        name: "日式小食"
      },
      {
        id: 5,
        name: "系列套餐"
      },
      {
        id: 6,
        name: "特色炖汤"
      },
      {
        id: 7,
        name: "下午茶"
      },
      {
        id: 8,
        name: "日式小食"
      },
      {
        id: 9,
        name: "滋味盖饭"
      },
      {
        id: 10,
        name: "系列套餐"
      },
    ],
    arr2: [{
        id: 0,
        value: "香辣味"
      },
      {
        id: 1,
        value: "盐焗味"
      },
      {
        id: 2,
        value: "蒜香味"
      },
      {
        id: 3,
        value: "姜葱味"
      },
    ],

    height: 0,
    orderType: 0, //点菜类型
    restaurant: false, //餐厅点菜
    map_address: '',
    buycar_num: 0,
    block: false, //选规格
    foodtype: 0, //选规格种类
    foodInfo: {},
    bindId: 0,

    // buycar
    totalMoney: 0,
    chooseAll: false,
    arr: [],
    arr3: [],
    // order
    orderOk: false,
    // me
    img: ''
  },
  changeIndicatorDots() {
    this.setData({
      indicatorDots: !this.data.indicatorDots
    })
  },

  changeAutoplay() {
    this.setData({
      autoplay: !this.data.autoplay
    })
  },

  intervalChange(e) {
    this.setData({
      interval: e.detail.value
    })
  },
  // 订单列表
  orderList: function () {
    var that = this
    wx.request({
      url: 'https://calamar.top:8081/order/orderList', //仅为示例，并非真实的口址
      method: 'post',
      data: {
        shopId: '1',
        userId: '18721260590',
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          orderArr: res.data.data.map(ele=>{
            // return Object.assign({},ele,{orderTime:dayjs(ele.orderTime).format("YYYY-MM-DD HH:mm:ss")})
            return Object.assign({},ele)
          }),
          pageType:3
        })
      }
    })
  },

  searchBuyCard() {
    var that = this
    wx.request({
      url: 'https://calamar.top:8081/shoppingCart/shoppingCartList', //仅为示例，并非真实的口址
      method: 'post',
      data: {
        shopId: '1',
        userId: '18721260590'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          arr: res.data.data?.products.map(ele => {
            return {
              id: ele.id,
              img: ele.icon,
              name: ele.name,
              selectCount: ele.num,
              price: Number(ele.price / 100).toFixed(2),
              selected: true,
              productId: ele.productId,
              labelId: ele.labelId,
            }
          })
        })
        let arr = that.data.arr
        let arr2 = arr.filter(ele => {
          return ele.selected
        })
        let total = 0
        arr2.forEach(ele => {
          total += ele.price * ele.selectCount
        })
        that.setData({
          totalMoney: total,
          buycar_num: arr2.length,
        });
      }
    })
  },
  durationChange(e) {
    this.setData({
      duration: e.detail.value
    })
  },
  carousel() {
    var that = this
    wx.request({
      url: 'https://calamar.top:8081/banner/bannerList', //仅为示例，并非真实的口址
      method: 'post',
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          background: res.data.data
        })
      }
    })
  },
  onLoad: function () {
    var that = this
    this.searchBuyCard()
    this.carousel()
    this.searchBalance()

    let data={
      "userId":"18721260590"
    }
    wx.request({
      url: 'https://calamar.top:8081/banner/bannerList',
      method: 'POST',
      data:data,    //参数为键值对字符串
      header: {
        //设置参数内容类型为x-www-form-urlencoded
        'content-type':'application/json'
      },
      success: function (res) {
        console.log(res.data)
        that.setData({
          imageList: res.data.data
        })
      }

    })


    wx.request({
      url: 'https://calamar.top:8081/product/productTypeList', //仅为示例，并非真实的口址
      method: 'post',
      data: {
        shopId: '1',
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          menu: res.data.data
        })
        wx.request({
          url: 'https://calamar.top:8081/product/userProductList',
          method: 'post',
          data: {
            userId: '18721260590',
            typeId: res.data.data[0].id
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            that.setData({
              arr3: res.data.data.map(ele => {
                return Object.assign({}, ele, {
                  unitPrice: Number(ele.unitPrice / 100).toFixed(2)
                })
              })
            })
          }
        })
      }
    })
    // wx.getLocation({
    //   type: 'gcj02',
    //   success: function (res) {
    //     var latitude = res.latitude
    //     var longitude = res.longitude
    //     wx.request({
    //       url: 'http://api.map.baidu.com/geocoder/v2/?ak=LClVsCTaW2aH8MzuviP1YMymrHWOIVvg&coordtype=gcj02ll&location=' + latitude + ',' + longitude + '&output=json&pois=0',
    //       method: "get",
    //       success: function (res) {
    //         var address = res.data.result.formatted_address;
    //         address = address.split('省')[1].split('市')[1];
    //         that.setData({
    //           map_address: address
    //         })
    //         console.log(that.data.map_address)
    //       }
    //     })
    //   }
    // })
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          height: (res.windowHeight * .57) + 'px'
        })
      }
    });
  },
  searchBalance: function () {
    var that = this
    wx.request({
      url: 'https://calamar.top:8081/balance/balanceInfo',
      method: 'post',
      data: {
        userId: '18721260590',
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          balance: Number(res.data.data.balance/100).toFixed(2)
        })
      }
    })
  },
  turnMenu: function (e) {
    var that = this
    wx.request({
      url: 'https://calamar.top:8081/product/userProductList',
      method: 'post',
      data: {
        userId: '18721260590',
        typeId: e.target.dataset.id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          arr3: res.data.data.map(ele => {
            return Object.assign({}, ele, {
              unitPrice: Number(ele.unitPrice / 100).toFixed(2)
            })
          })
        })
        that.setData({
          orderType: e.target.dataset.index
        })

      }
    })
  },
  chooseType: function (e) {
    var type = e.currentTarget.dataset.id;
    if (type == 1 && this.data.restaurant == true) {
      wx.setNavigationBarTitle({
        title: '点餐'
      })
    } else if (type == 1 && this.data.restaurant != true) {
      wx.setNavigationBarTitle({
        title: '商品'
      })
    } else if (type == 2) {
      wx.setNavigationBarTitle({
        title: '购物车'
      })
    } else if (type == 3) {
      wx.setNavigationBarTitle({
        title: '订单'
      })
      this.orderList()
    } else if (type == 4) {
      wx.setNavigationBarTitle({
        title: '我的'
      })
    }
    this.setData({
      pageType: type
    })
  },
  // index
  searchKey: function (e) {
    this.setData({
      searchKey: e.detail.value
    })
  },
  searchBtn: function () {
    var keyWork = this.data.searchKey;
    wx.redirectTo({
      url: '../test/test',
    })
    wx.request({
      url: '',
      data: {

      },
      success: function (res) {

      }
    })
  },
  tabChange: function (e) {
    var type = e.currentTarget.dataset.id;
    this.setData({
      orderOrBusiness: type
    })
  },
  //打开红包
  getPag: function () {
    this.setData({
      open: true,
      page: false
    })
  },
  //关闭红包
  hasGet: function () {
    this.setData({
      open: false
    })
  },
  toSetmenu: function () {
    wx.navigateTo({
      url: '../setmenu/setmenu'
    })
  },
  saoma: function () {
    var that = this;
    wx.scanCode({
      onlyFromCamera: true,
      success: (res) => {
        console.log(res);
        that.setData({
          restaurant: true
        })
        wx.setNavigationBarTitle({
          title: '点餐'
        })
      },
      fail: (res) => {
        that.setData({
          restaurant: false
        });
      }
    })
  },
  toFoodDetail: function () {
    wx.navigateTo({
      url: '../detail/detail',
    })
  },
  reduce: function (e) {
    var i = e.currentTarget.dataset.id;
    var info = e.currentTarget.dataset.info;
    var arr3 = this.data.arr3;
    var that = this
    if (arr3[i].selectCount > 1) {
      wx.showToast({
        title: '多规格商品只能去购物车删除哦',
        duration: 2000
      })
    } else {
      if (arr3[i].selectCount > 0) {
        arr3[i].selectCount = parseInt(arr3[i].selectCount) - 1;
        this.setData({
          arr3: arr3
        })
        wx.request({
          url: 'https://calamar.top:8081/shoppingCart/reduceShoppingCart',
          method: 'post',
          data: {
            userId: '18721260590',
            productId: info.id,
            shopId: "1",
            shoppingCartPage: 0
          },
          header: {
            'content-type': 'application/json' // 默认值
          },
          success(res) {
            that.searchBuyCard()

          }
        })
      }
    }
  },
  reduce2: function (e) {
    var i = e.currentTarget.dataset.id;
    var info = e.currentTarget.dataset.info;
    var arr3 = this.data.arr3;
    var that = this
    if (arr3[i].selectCount > 0) {
      arr3[i].selectCount = parseInt(arr3[i].selectCount) - 1;
      this.setData({
        arr3: arr3
      })
      wx.request({
        url: 'https://calamar.top:8081/shoppingCart/reduceShoppingCart',
        method: 'post',
        data: {
          userId: '18721260590',
          productId: info.id,
          shopId: "1",
          shoppingCartPage: 0
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {
          that.searchBuyCard()

        }
      })
    }
  },
  add: function (e) {
    var i = e.currentTarget.dataset.id;
    var arr3 = this.data.arr3;
    var arr = arr3[i]?.labels;
    var info = e.currentTarget.dataset.info;
    this.setData({
      block: true,
      arr2: arr,
      bindId: i,
      specifications: {
        productName: e.currentTarget.dataset.info.productName,
        labelTypeName: e.currentTarget.dataset.info?.labels[0]?.labelTypeName,
        labels: e.currentTarget.dataset.info.labels[0].labels,
        info: info
      }
    })

  },
  add2: function (e) {
    var that = this
    var i = e.currentTarget.dataset.id;
    var arr3 = this.data.arr3;
    var info = e.currentTarget.dataset.info;
    arr3[i].selectCount = parseInt(arr3[i].selectCount) + 1;
    this.setData({
      arr3: arr3
    })
    wx.request({
      url: 'https://calamar.top:8081/shoppingCart/addShoppingCart',
      method: 'post',
      data: {
        userId: '18721260590',
        productId: info.id,
        labelId: "",
        shopId: "1",
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.searchBuyCard()
      }
    })

  },
  close: function () {
    this.setData({
      block: false
    })
  },
  resetNum: function (e) {
    var type = e.currentTarget.dataset.id;
    this.setData({
      foodtype: type,
      foodInfo: e.currentTarget.dataset.info
    })
  },
  submit: function () {
    var that = this
    var i = this.data.bindId;
    var arr3 = this.data.arr3;
    arr3[i].selectCount = parseInt(arr3[i].selectCount) + 1
    wx.request({
      url: 'https://calamar.top:8081/shoppingCart/addShoppingCart',
      method: 'post',
      data: {
        userId: '18721260590',
        productId: that.data.specifications?.info?.id,
        labelId: that.data.foodInfo?.id,
        shopId: "1",
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        that.setData({
          block: false,
          arr3: arr3
        })
        that.searchBuyCard()
      }
    })
  },
  getAddress: function () {
    var that = this;
    wx.chooseLocation({
      success: function (res) {
        if (res.address.length > 10) {
          res.address = res.address.substr(0, 10) + '...'
        }
        that.setData({
          map_address: res.address
        })
      },
    })
  },
  buyCardLink: function () {
    this.setData({
      pageType: 2
    })
  },
  takeOut: function () {
    this.setData({
      restaurant: false
    })
    wx.setNavigationBarTitle({
      title: '商品'
    })
  },
  // buycar
  del: function (e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '确定删除吗',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: 'https://calamar.top:8081/shoppingCart/reduceShoppingCart',
            method: 'post',
            data: {
              productId: e.currentTarget.dataset.info.productId,
              labelId: e.currentTarget.dataset.info.labelId,
              userId: '18721260590',
              shoppingCartPage: '1',
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            success(res) {
              that.setData({
                arr3: res.data.data.map(ele => {
                  return Object.assign({}, ele, {
                    unitPrice: Number(ele.unitPrice / 100).toFixed(2)
                  })
                })
              })
              that.searchBuyCard()

            }
          })


          // var index = parseInt(e.currentTarget.dataset.id);
          // var arr = that.data.arr;
          // var totalMoney = that.data.totalMoney;
          // var buycar_num = that.data.buycar_num;
          // if (arr[index].selected) {
          //   totalMoney -= Number(arr[index].price * arr[index].selectCount);
          //   buycar_num -= Number(arr[index].selectCount);
          // }
          // arr.splice(index, 1);
          // that.setData({
          //   arr: arr,
          //   totalMoney: totalMoney,
          //   buycar_num: buycar_num
          // });
        }
      }
    })
  },
  choose: function (e) {
    var index = parseInt(e.currentTarget.dataset.id);
    var selected = this.data.arr[index].selected;
    var arr = this.data.arr;
    var totalMoney = this.data.totalMoney;
    var buycar_num = this.data.buycar_num;
    arr[index].selected = !selected;
    if (arr[index].selected) {
      totalMoney += Number(arr[index].price * arr[index].selectCount);
      buycar_num += Number(arr[index].selectCount);
    } else {
      totalMoney -= Number(arr[index].price * arr[index].selectCount);
      buycar_num -= Number(arr[index].selectCount);
    }
    totalMoney = Number(totalMoney).toFixed(2);
    this.setData({
      arr: arr,
      totalMoney: Number(totalMoney),
      buycar_num: buycar_num
    });
  },
  toSubmit: function () {
    var that = this
    let a = that.data.arr.filter(ele => {
      return ele.selected
    }).map(e => {
      return {
        id: e.id,
        name: e.name,
        price: e.price,
        productId: e.productId,
        img: e.img,
        selectCount: e.selectCount,
        labelId: e.labelId
      }
    })
    wx.setStorage({
      key: 'arrSelected',
      data: a
    })
    if (that.data.totalMoney != '0') {
      wx.navigateTo({
        url: '../submitOrder/submitOrder?',
        // url: '../submitOrder/submitOrder',
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '请选择商品',
        success(res) {
          if (res.confirm) {} else if (res.cancel) {
            console.log('用户点击确定')
          }
        }
      })
    }


  },
  numAdd: function (e) {
    var info = e.currentTarget.dataset.info;
    console.log(info, 'kkk')
    var index = parseInt(e.currentTarget.dataset.id);
    var selected = this.data.arr[index].selected;
    var arr = this.data.arr;
    var totalMoney = this.data.totalMoney;
    var buycar_num = this.data.buycar_num;
    arr[index].selectCount = Number(arr[index].selectCount) + 1;
    if (selected == true) {
      totalMoney += Number(arr[index].price);
      buycar_num += 1;
    }
    totalMoney = Number(totalMoney).toFixed(2);
    this.setData({
      arr: arr,
      totalMoney: Number(totalMoney),
      buycar_num: buycar_num
    });
    wx.request({
      url: 'https://calamar.top:8081/shoppingCart/addShoppingCart',
      method: 'post',
      data: {
        userId: '18721260590',
        productId: info.productId,
        labelId: info.labelId ? info.labelId : '',
        shopId: "1",
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {

      }
    })
  },
  numReduce: function (e) {
    var index = parseInt(e.currentTarget.dataset.id);
    var info = e.currentTarget.dataset.info;
    var arr = this.data.arr;
    if (arr[index].selectCount > 1) {
      var selected = arr[index].selected;
      var totalMoney = this.data.totalMoney;
      var buycar_num = this.data.buycar_num;
      arr[index].selectCount = Number(arr[index].selectCount) - 1;
      if (selected == true) {
        totalMoney -= Number(arr[index].price);
        buycar_num -= 1;
      }
      totalMoney = Number(totalMoney).toFixed(2);
      this.setData({
        arr: arr,
        totalMoney: Number(totalMoney),
        buycar_num: buycar_num
      });
      wx.request({
        url: 'https://calamar.top:8081/shoppingCart/reduceShoppingCart',
        method: 'post',
        data: {
          userId: '18721260590',
          productId: info.productId,
          shopId: "1",
          shoppingCartPage: 1
        },
        header: {
          'content-type': 'application/json' // 默认值
        },
        success(res) {}
      })
    }
  },
  // order
  orderOk: function () {
    this.setData({
      orderOk: true
    })
  },
  okCancel: function () {
    this.setData({
      orderOk: false
    })
  },
  calling: function () {
    wx.makePhoneCall({
      phoneNumber: '18316588252',
      success: function () {
        console.log("拨打电话成功！")
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
  },
  okOk: function () {
    this.setData({
      orderOk: false
    })
  },
  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },
  toMyPackage: function () {
    wx.navigateTo({
      url: '../myPackage/myPackage'
    })
  },
  toMyAddress: function () {
    wx.navigateTo({
      url: '../address/address'
    })
  },
  toDetail: function () {
    wx.navigateTo({
      url: '../orderDetail/orderDetail'
    })
  }
})